using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
using IQToolkit.Data.Firebird;
using Sio.Mdm.Entities;
using IQToolkit;

namespace Sio.Mdm.BL.Base
{
    public class QueryCommand
    {
        private string _sqlQuery;

        public string SqlQuery
        {
            get 
            {
                if (Count != Int32.MaxValue && Count > -1 && Start > -1)
                {
                    string sql = _sqlQuery.Replace("SELECT", "");
                    return String.Format("SELECT FIRST {0} SKIP {1} {2}", Count, Start - 1, sql);
                }

                return _sqlQuery; 
            }
            set 
            { 
                _sqlQuery = value; 
            }
        }
        private int _start = -1;
        public int Start
        {
            get
            {
                return _start;
            }
            set
            {
                _start = value;
            }
        }
        private int _end = -1;
        public int Count
        {
            get
            {
                return _end;
            }
            set
            {
                _end = value;
            }
        }

        private Dictionary<string, object> _sqlParams;

        public Dictionary<string, object> SqlParams
        {
            get { return _sqlParams; }
            set { _sqlParams = value; }
        }

        public QueryCommand(string sqlQuery, Dictionary<string, object> sqlParams)
        {
            this._sqlParams = sqlParams;
            this._sqlQuery = sqlQuery;
        }

        public QueryCommand(string sqlQuery)
        {
            this._sqlQuery = sqlQuery;
            this._sqlParams = new Dictionary<string, object>();
        }

        public override string ToString()
        {
            string result = SqlQuery;
            foreach (var param in SqlParams)
            {
                string value;
                if (param.Value.GetType().IsValueType)
                    value = param.Value.ToString();
                else if (param.Value.GetType() == typeof(DateTime))
                    value = String.Format("'{0}'", param.Value.ToString());
                else
                    value = String.Format("'{0}'", param.Value.ToString());
                result = result.Replace(String.Format("@{0}", param.Key), value);
            }
            return result;
        }
    }
}
